<?php


namespace app\service;

use think\facade\Db;
use app\model\ModelTask;
use app\model\ModelUserTask;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * Class Service
 * @package app\service
 */
class TaskService extends BaseService
{
    /**
     * 前端用户领取任务
     * @param int $user_id
     * @param int $task_id
     * @param int $canGetTaskCount 每日可以领取的任务数量，用户VPI级别不同，领取的任务数量和单价也不同
     * @return array
     */
    public function insertMyTask(int $user_id, int $task_id,int $canGetTaskCount): array
    {
        if (empty($user_id) || empty($task_id)) {
            return $this->error('失败', 0);
        }
        $taskInfo = $this->getTaskDetailByTaskID($task_id);
        if (empty($taskInfo['data'])) {
            return $this->error('无效任务', 0);
        }
        $todayTaskCount = $this -> countUserTodayTaskByUserId($user_id);
        //var_dump($todayTaskCount);
        if($todayTaskCount['status'] == 1 && !empty($todayTaskCount['data'])) {
             if($todayTaskCount['data'] >= $canGetTaskCount){
                 return $this->error('抱歉,已超出当前每天可领取的任务总量,您可以选择提升等级', 0);
             }
        }
        $userTaskInfo = $this -> getUserTaskByTaskIDAndUserID($user_id,$task_id);
        if ($userTaskInfo['status'] == 1 && !empty($userTaskInfo['data'])) {
            return $this->error('不可以重复领取任务', 0);
        }
        //任务状态 0:可用 1:任务次数已用完,task_remainder = 0 无可领取任务
        if ($taskInfo['data']['task_status'] == 1 || $taskInfo['data']['task_remainder'] == 0) {
            return $this->error('任务已抢完', 0);
        }
        $where = [
            'id' => $task_id
        ];
        $task_remainder = $taskInfo['data']['task_remainder'] - 1; //剩余任务数量
        $dataTask = [
            'task_remainder' => $task_remainder,
            'task_complete' => $taskInfo['data']['task_complete'] + 1,
        ];
        if ($task_remainder = 0) {
            $dataTask['task_status'] = 1; //任务状态 0:可用 1:任务次数已用完
        }
        $modelTask = new ModelTask();
        $result = $modelTask->where($where)->save($dataTask);
        if ($result) {
            $modelUserTask = new ModelUserTask();
            $t = time();
            $data = [
                'user_id' => $user_id,
                'task_id' => $task_id,
                'task_start_time_day' => date("Ymd ", $t),
                'task_start_time' => $t,
                'task_status' => 1,
                'is_delete' => 0
            ];
            $result = $modelUserTask->insertGetId($data);
            return $this->success('成功', $result);
        } else {
            return $this->error('任务领取失败', 0);
        }
    }

    /**
     * 通过id获取该用户已领取任务列表--支持分页
     * @param int $userId
     * @param int $status 领取任务后的状态，枚举值：1:已领取未开始 2: 提交审核 3:已领取已完成 4 已取消
     * @param string $task_start_time 领取任务的时间，默认最近7天;客户端传入的参数：2021-04-04
     * @param string $page
     * @param string $size
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserTaskByUserId(int $userId, int $status, string $task_start_time, string $page, string $size): array
    {
        if ($page <= 1) {
            $page = 1;
        }
        if ($size < 10) {
            $size = 10;
        }
        if ($status < 1 || $status > 4) {
            $status = 1;
        }
        if (!empty($task_start_time)) {
            $task_start_time = strtotime($task_start_time);
        } else {
            $task_start_time = strtotime('-7 days');
        }
        $userTaskModel = new ModelUserTask();
        $taskModel = new ModelTask();
        $where = [
                    ['user_id', '=', $userId],
                    ['task_start_time', '>', $task_start_time ],
                    ['task_status' , '=', $status],
                    ['is_delete' , '=', 0],
                ];
        $taskIDList = $userTaskModel->field('task_id')->where($where) ->page($page, $size)->select();
        //dump($userTaskModel-> getLastSql());die();
        if (!empty($taskIDList)) {
            $taskId = [];
            foreach ($taskIDList as $val) {
                $taskId[] = $val['task_id'];
            }
            $taskList = $taskModel->where(['is_delete' => 0])
                ->whereIn('id', $taskId)
                ->page($page, $size)
                ->select()
                ->toArray();
            return $this->success('成功', $taskList);
        } else {
            return $this->error('失败', 0);
        }
    }


    /**
     *通过id获取该用户已领取任务列表
     * @param int $userId 用户ID,当用户ID=0，则是要查全部任务数据
     * @param array $condition 查询条件
     * 通用查询条件
     * @return array|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author qt
     */
    public function getUserTaskByCondition(int $userId, array $condition): ?array
    {
        $userTaskModel = new ModelUserTask();
        return null;
    }

    /**
     * @param int $task_completion_time 查询指定日期的完成任务的用户排名，按任务从高到底排序，默认：查询60天内任务
     * @return array $list 用户的任务数量
     */
    public function countUserTaskGroupAll(int $task_completion_time): array
    {
        if (empty($task_completion_time)) {
            $task_completion_time = strtotime("-60 day");
        }
        $list = Db::query("select *
from (
select u.mobile,count(*) task_num
from user_task ut
    inner join user u on u.id = ut.user_id
where ut.task_status = ?
and ut.task_complete_time >= ?
group by ut.user_id      
) t
order by t.task_num desc
limit 5", [3, $task_completion_time]);
        return $this->success('成功', $list);
    }

    /**
     * @param int $page 获取第几页的数据
     * @param int $size 分页尺寸;只支持，5,10,20分页尺寸
     * @param string $lv 任务等级：1,2,3，默认查找全部等级数据
     * @param int $user_id 当前用户ID
     * @param string $task_type 任务类型:101 微视; 201 小红书; 301 快手; 401 抖音;
     * @return array 返回推荐任务的数组
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getRecommendTask(int $page, int $size = 10, string $lv,int $user_id,string $task_type): array
    {
        if(empty($user_id)){
            return $this -> error('用户ID必传');
        }
        $currentStart  = 0 ;
        $currentEnd  = 0 ;
        if ($size < 10) {
            $size = 10;
        }
        if($size != 10 && $size != 20 && $size != 5){
            $size = 10;
        }
        if ($page <= 0) {
            $page = 0;
            $currentEnd  = $size ;
        }else{
            if($page > 50){
                $page = 50;
            }
            $currentStart  = $page * $size;
            $currentEnd  = $currentStart + $size;
        }
        $my_sql = ' and  1= 1';
        if(!empty($lv)){
            if ($lv < 1 || $lv > 3) {
                $lv = 1;
            }
            $my_sql = ' and  t.task_lv = ' . $lv;
        }
        if ($task_type > 401) {
            $task_type = 101;
        }
        if(!empty($task_type)){
            $my_sql .= ' and  t.task_type = ' . $task_type.' ';
        }
//dump($my_sql);
  //      dump($user_id,$currentStart,$currentEnd);
        $exe_sql = "select *
from task t
where t.task_status =0
and t.is_delete =0 
{$my_sql} 
and t.task_total > 0
and t.task_remainder > 0
     and t.id not in (
           select task_id from user_task where user_id = {$user_id}
     )
     order by t.id desc
     limit {$currentStart},{$currentEnd}";
       // var_dump($exe_sql);die();
        $list = Db::query($exe_sql);
        //dump($list);die();
        return $this->success('成功', $list);
    }

    /**
     * 查询某个用户的任务，支持根据状态条件查，已删除的任务不可以查询，但是状态：4 的取消状态可以查
     * @param int $user_id 必填参数，用户ID
     * @param int $status 非必填参数，任务状态值
     * @return array 返回该用户的任务ID列表
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserTaskIdByUserid(int $user_id,int $status=0) : array
    {
        if (empty($user_id)) {
            return $this->error('参数错误');
        }
        if ($status < 1 || $status > 4) {
            return $this->error('参数错误');
        }
        $where = [
            'user_id' => $user_id,
            'is_delete' => 0,
        ];
        if ($status > 0) {
            $where['task_status'] = $status;
        }
        $userTaskModel = new ModelUserTask();
        $result = $userTaskModel->where($where)->field('task_id')->select();
        return $this->success('成功', $result);
    }

    /**
     * 获取用户领取的任务的详情
     * @param int $user_id 用户ID
     * @param int $task_id 任务ID
     * @return array 返回某个用户某个任务
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTaskDetailByTaskIDAndUserID(int $user_id, int $task_id): array
    {
        if (empty($user_id) || empty($task_id)) {
            return $this->error('参数错误');
        }
        $userTaskModel = new ModelUserTask();
        $where = [
            'user_id' => $user_id,
            'task_id' => $task_id,
            'is_delete' => 0,
        ];
        $isHaveTask = $userTaskModel->where($where)->count();
        if ($isHaveTask > 0) {
            $result = $this->getUserTaskByTaskIDAndUserID($user_id,$task_id);
            if ($result['status'] == 1) {
                return $this->success($result['status'], $result['data']);
            } else {
                return $this->error($result['status']);
            }
        } else {
            return $this->error('任务id='.$task_id.'的任务不存在');
        }
    }

    /**
     * 获取任务详情--通过任务ID
     * @param int $task_id
     * @param string $fields
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTaskDetailByTaskID(int $task_id,string $fields='*'): array
    {
        if (empty($task_id)) {
            return $this->error('参数错误');
        }
        $modelTask = new ModelTask();
        $where = [
            'id' => $task_id,
            'is_delete' => 0,
        ];
        $detail = $modelTask->where($where)->field($fields)->findOrEmpty()->toArray();
        //dump($modelTask->getLastSql());die();
        return $this->success('成功', $detail);
    }

    /**
     * 用户提交完成任务的数据
     * @param int $user_id 用户ID
     * @param int $task_id 任务ID
     * @param string $files  上传的图片信息
     * @param string $remark 用户完成任务的备注
     * @return array 返回某个用户某个任务的ID
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function commitUserTaskData(int $user_id, int $task_id,string $files,string $remark): array
    {
        if (empty($user_id) || empty($task_id)) {
            return $this->error('参数错误');
        }
        //这里还得设计上传文件表,先搞个字段吧
        //任务状态：1:已领取未开始 2: 提交审核 3:已领取已完成 4 已取消
        $result = $this->updateUserTaskStatusByID($user_id, $task_id,2,$files,$remark);
        //return $this->success('成功', $result);
        if($result['status'] == 1){
            return $this->success('成功', $result['data']);
        }else{
            return $this->error('保存失败');
        }
    }


    /**
     * 更新用户任务状态--根据用户ID和任务ID;
     * @param int $user_id
     * @param int $task_id
     * @param int $status 任务状态：1:已领取未开始 2: 提交审核 3:已领取已完成 4 已取消
     * @param string $fiels 完成任务的截图
     * @param string $remark 用户提交的备注
     * @return array
     */
    public function updateUserTaskStatusByID(int $user_id,int $task_id,int $status,string $fiels,string $remark) : array
    {
        if (empty($user_id) || empty($task_id) || empty($status)) {
            return $this->error('参数错误');
        }
        if ($status < 0 || $status > 4) {
            return $this->error('状态值严重错误');
        }
        $userTaskModel = new ModelUserTask();
        $t = time();
        $where = [
            'user_id' => $user_id,
            'task_id' => $task_id,
            'is_delete' => 0,
        ];
        $data = [
            'task_complete_time' => $t,
            'task_status' => $status  //1:已领取未开始 2: 提交审核 3:已领取已完成 4 已取消
        ];
        if(!empty($fiels)){
            $data['complete_files'] = $fiels;
        }
        if(!empty($remark)){
            $data['remark'] = $remark; //直接用用户的备注覆盖，这里有点问题，先不管了
        }
        $result = $userTaskModel->where($where)->save($data);
        if($result){
            return $this->success('成功', $result);
        }else{
            return $this->error('保存失败');
        }
    }

    /**
     * 获取某个用户领取的任务信息
     * @param int $user_id 用户ID
     * @param int $task_id 任务ID
     * @return array 返回某个用户某个任务
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserTaskByTaskIDAndUserID(int $user_id, int $task_id): array
    {
        if (empty($user_id) || empty($task_id)) {
            return $this->error('参数错误');
        }
        $userTaskModel = new ModelUserTask();
        $where = [
            'user_id' => $user_id,
            'task_id' => $task_id,
            'is_delete' => 0,
        ];
        $result = $userTaskModel->where($where)->findOrEmpty() -> toArray();
        return $this->success('成功', $result);
    }

    /**
     * 统计某天某个用户领取的任务数量，不管是什么状态，领取了就算;默认是当天
     * @param int $user_id 必传项目，用户ID
     * @param int $day  非必传项目，领取任务日期，默认是当天
     * @return array
     */
    public function countUserTodayTaskByUserId(int $user_id,int $day=0) : array{
        if (empty($user_id)) {
            return $this->error('参数错误');
        }
        if(empty($day) || $day < 20210101){
            $day =  date("Ymd ", time());
        }else{
            if($day > date("Ymd ", time())){
                return $this->error('领取任务日期不可以大于当天');
            }
        }
        $userTaskModel = new ModelUserTask();
        $where = [
            'user_id' => $user_id,
            'is_delete' => 0,
            'task_start_time_day' => $day
        ];
        $result = $userTaskModel->where($where)->count();
        //echo $userTaskModel->getLastSql();
        return $this->success('成功', $result);
    }

    /**
     * 审核用户完任务的方法
     * @param int $id
     * @param int $check_vale
     * @param int $check_user_id
     * @return array
     */
    public function checkUserCompleteTaskById(int $id,int $check_vale,int $check_user_id) : array
    {
        //更新任务状态
        if (empty($id) || empty($check_vale) || empty($check_user_id)) {
            return $this->error('参数错误');
        }
        //审核结果值只有两个：3:已领取已完成; 4 已取消;
        if ($check_vale <> 3 && $check_vale <> 4) {
            return $this->error('审核状态值错误');
        }
        $userTaskModel = new ModelUserTask();
        $userTaskInfo = $this->getUerTaskInfoById($id);
        if ($userTaskInfo['status'] == 0) {
            return $this->error($userTaskInfo['msg']);
        }
        $user_id = $userTaskInfo['data']['user_id'];
        $task_id = $userTaskInfo['data']['task_id'];
        $task_fields = 'id,task_profit,task_lv,task_status,task_type,task_total,task_remainder';
        $task = $this->getTaskDetailByTaskID($task_id, $task_fields);
        if ($task['status'] == 0) {
            return $this->error($task['msg']);
        }
        $where = [
            'id' => $id,
            'is_delete' => 0
        ];
        $data = [
            'task_status' => $check_vale,
            'update_time' => time(),
            'remark' => $userTaskInfo['data']['remark'] . '审核通过',
        ];
        $result = $userTaskModel->where($where)->save($data);
        if ($result) {
            //审核通过
            if($check_vale ==3){
                //分配利益  给当前用户账号加钱，插入收入流水
                $userService = new UserAccountService();
                $amount = $task['data']['task_profit'];//完成任务奖励金额
                //插入具体业务数据
                $task_complete = $userService->insertUserAccountTaskComplete($user_id, $task_id, $id, $amount);
                $info_id = 0;
                if ($task_complete['status'] == 1) {
                    $info_id = $task_complete['data'];
                } else {
                    return $this->error('用户任务信息表数据查询错误');
                }
                //插入用户收入表
                $i = $userService->insertUserAccountIncome($user_id, $amount, 201, $info_id);
                if ($i['status'] == 1) {
                    //更新用户账号收入
                    $u = $userService->addUserAccountBalance($user_id, $amount,201);
                    if ($u['status'] == 0) {
                        return $this->error('更新用户账号失败');
                    } else {
                        return $this->success('审核成功', $u['data']);
                    }
                } else {
                    return $this->error('用户收入插入失败');
                }
            }else {
                return $this->success('审核成功--拒绝', 1);
            }
        }
    }

    /**
     * 通过信息ID获取用户领取的任务的数据信息
     * @param int $id 用户任务表的ID
     * @return array
     */
    public function getUerTaskInfoById(int $id) : array
    {
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $userTaskModel = new ModelUserTask();
        $result = $userTaskModel->where('id', $id)->findOrEmpty() -> toArray();
        return $this->success('成功', $result);
    }
}